package com.sky.his.api.front.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.bean.BeanUtil;
import com.sky.his.api.common.PageUtils;
import com.sky.his.api.common.R;
import com.sky.his.api.config.sa_token.StpCustomerUtil;
import com.sky.his.api.front.controller.form.CreatePaymentForm;
import com.sky.his.api.front.controller.form.RefundForm;
import com.sky.his.api.front.controller.form.SearchOrderByPageForm;
import com.sky.his.api.front.controller.form.SearchPaymentResultForm;
import com.sky.his.api.front.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController("FrontOrderController")
@Slf4j
@RequestMapping("/front/order")
public class OrderController {

    @Resource
    private OrderService orderService;

//    @Resource
//    private WechatApiProvider wechatApiProvider;

    @PostMapping("/createPayment")
    @SaCheckLogin(type = StpCustomerUtil.TYPE)
    public R cratePayment(@RequestBody @Valid CreatePaymentForm form) {
        int customerId = StpCustomerUtil.getLoginIdAsInt();
        Map param = BeanUtil.beanToMap(form);
        param.put("customerId", customerId);
//        HashMap map = orderService.createPayment(param);
        HashMap map = null;
        if (map == null) {
            return R.ok().put("illegal", true);
        } else {
            return R.ok().put("illegal", false).put("result", map);
        }
    }

    @PostMapping("/searchByPage")
    @SaCheckLogin(type = StpCustomerUtil.TYPE)
    public R searchByPage(@Valid @RequestBody SearchOrderByPageForm form) {
        int customerId = StpCustomerUtil.getLoginIdAsInt();
        int page = form.getPage();
        int length = form.getLength();
        int start = (page - 1) * length;
        Map param = BeanUtil.beanToMap(form);
        param.put("start", start);
        param.put("customerId", customerId);
        PageUtils pageUtils = orderService.searchByPage(param);
        return R.ok().put("result", pageUtils);
    }

    @PostMapping("/searchPaymentResult")
    @SaCheckLogin(type = StpCustomerUtil.TYPE)
    public R searchPaymentResult(@Valid @RequestBody SearchPaymentResultForm form) {
        boolean bool = orderService.searchPaymentResult(form.getOutTradeNo());
        return R.ok().put("result", bool);
    }

    

    @PostMapping("/refund")
    @SaCheckLogin(type = StpCustomerUtil.TYPE)
    public R refund(@RequestBody @Valid RefundForm form) {
        int customerId = StpCustomerUtil.getLoginIdAsInt();
        form.setCustomerId(customerId);
        Map param = BeanUtil.beanToMap(form);
        boolean bool = orderService.refund(param);
        return R.ok().put("result", bool);
    }

//    @SneakyThrows
//    @PostMapping("/refundCallback")
//    public Map paymentCallback(
//            @RequestHeader("Wechatpay-Serial") String serial,
//            @RequestHeader("Wecharpay-Signature") String signature,
//            @RequestHeader("Wecharpay-Timestamp") String timestamp,
//            @RequestHeader("Wecharpay-Nonce") String nonce,
//            HttpServletRequest request) {
//        String body = request.getReader().lines().collect(Collectors.joining());
//
//        ResponseSignVerifyParams params = new ResponseSignVerifyParams();
//        params.setWechatpaySerial(serial);
//        params.setWechatpayTimestamp(timestamp);
//        params.setWechatpayNonce(nonce);
//        params.setBody(body);
//
//        return wechatApiProvider.callback("his-vue").transactionCallback(params, data -> {
//            String status = data.getRefundStatus().toString;
//            if ("SUCCESS".equals(status)) {
//                String outRefundNo = data.getOutRefundNo();
//                boolean bool = orderService.updateRefundStatus(outRefundNo);
//                if (!bool) {
//                    log.error("订单状态更新失败");
//                } else {
//                    log.debug("退款流水号为" + outRefundNo + "的订单退款成功");
//                }
//            } else if ("ABNORMAL".equals(status)) {
//                //用户银行卡作废或者冻结，发送短信给用户手机,让客户联系客户执行手动退款
//            }
//        });
//    }


//    @SneakyThrows
//    @PostMapping("/paymentCallback")
//    public Map paymentCallback(
//            @RequestHeader("Wechatpay-Serial") String serial,
//            @RequestHeader("Wecharpay-Signature") String signature,
//            @RequestHeader("Wecharpay-Timestamp") String timestamp,
//            @RequestHeader("Wecharpay-Nonce") String nonce,
//            HttpServletRequest request) {
//        String body = request.getReader().lines().collect(Collectors.joining());
//
//        ResponseSignVerifyParams params = new ResponseSignVerifyParams();
//        params.setWechatpaySerial(serial);
//        params.setWechatpayTimestamp(timestamp);
//        params.setWechatpayNonce(nonce);
//        params.setBody(body);
//
//        return wechatApiProvider.callback("his-vue").transactionCallback(params, data -> {
//            String transactionId = data.getTransactionId();
//            String outTradeNo = data.getOutTradeNo();
//
//            boolean bool = orderService.updatePayment(new HashMap() {
//                {
//                    put("outTradeNo", outTradeNo);
//                    put("transactionId", transactionId);
//                }
//            });
//            if (bool) {
//                log.debug("订单付款成功，已更新订单状态");
//                Integer customerId = orderService.searchCustomerId(outTradeNo);
//                if (customerId == null) {
//                    log.error("没有查询到customerId");
//                } else {
//                    JSONObject json = new JSONObject();
//                    json.set("result", true);
//                    WebSocketService.sendInfo(json.toString(), "customer_" + customerId.toString());
//                }
//            } else {
//                log.error("订单信息更新失败");
//            }
//        });
//    }
}
